package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class RegisterController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, Object> paramMap) {
        Map<String, Object> result = new HashMap<>();
        try {
            String username = (String) paramMap.get("username");
            String password = (String) paramMap.get("password");
            String realName = (String) paramMap.get("realName");
            Integer gender = paramMap.get("gender") != null ? (Integer) paramMap.get("gender") : 0;
            Integer userType = paramMap.get("userType") != null ? (Integer) paramMap.get("userType") : null;

            if (username == null || username.trim().isEmpty() ||
                    password == null || password.trim().isEmpty() ||
                    realName == null || realName.trim().isEmpty() ||
                    userType == null) {
                result.put("success", false);
                result.put("message", "参数不完整");
                return result;
            }

            // 判断用户名是否存在
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("username", username);
            User existUser = userService.getOne(query);

            if (existUser != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }

            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setRealName(realName);
            newUser.setGender(gender);
            newUser.setUserType(userType);
            newUser.setStatus(1); // 启用状态

            boolean saved = userService.save(newUser);
            if (saved) {
                result.put("success", true);
                result.put("message", "注册成功");
            } else {
                result.put("success", false);
                result.put("message", "注册失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器异常");
        }
        return result;
    }
}
